<template>
  <view class="production-task-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">
        <text class="nav-title">任务中心</text>
      </block>
      <block slot="right">
        <view class="nav-right" @click="openFilterModal">
          <text class="cuIcon-filter"></text>
          <text class="filter-text">筛选</text>
        </view>
      </block>
    </cu-custom>

    <!-- 任务标签页 -->
    <view class="task-tabs bg-white margin-top-sm">
      <scroll-view scroll-x class="tab-scroll">
        <view class="tab-list">
          <view
            v-for="tab in taskTabs"
            :key="tab.key"
            :class="['tab-item', currentTab === tab.key ? 'active' : '']"
            @tap="switchTab(tab.key)"
          >
            <text class="tab-text">{{ tab.label }}</text>
            <view v-if="tab.count > 0" class="tab-badge">{{ tab.count }}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 搜索栏 -->
    <view v-if="showSearch" class="search-section bg-white margin-top-sm">
      <view class="search-wrapper padding">
        <view class="search-input-box">
          <input
            v-model="searchKeyword"
            class="search-input"
            placeholder="搜索任务名称、工种或负责人"
            @input="onSearch"
          />
          <text class="cuIcon-search search-icon"></text>
        </view>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <view v-if="showFilterModal" class="filter-modal" @tap="closeFilterModal">
      <view class="filter-content" @tap.stop>
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="cuIcon-close" @tap="closeFilterModal"></text>
        </view>

        <scroll-view scroll-y class="filter-body">
          <!-- 任务状态 -->
          <view class="filter-section">
            <text class="section-title">任务状态</text>
            <view class="filter-options">
              <view
                v-for="status in statusOptions"
                :key="status.value"
                :class="[
                  'filter-option',
                  filterParams.status === status.value ? 'active' : '',
                ]"
                @tap="selectFilter('status', status.value)"
              >
                <text>{{ status.label }}</text>
              </view>
            </view>
          </view>

          <!-- 工种类型 -->
          <view class="filter-section">
            <text class="section-title">工种类型</text>
            <view class="filter-options">
              <view
                v-for="workType in workTypeOptions"
                :key="workType.value"
                :class="[
                  'filter-option',
                  filterParams.workType === workType.value ? 'active' : '',
                ]"
                @tap="selectFilter('workType', workType.value)"
              >
                <text>{{ workType.label }}</text>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="filter-footer">
          <button class="reset-btn" @tap="resetFilter">重置</button>
          <button class="confirm-btn" @tap="applyFilter">确定</button>
        </view>
      </view>
    </view>

    <!-- 任务内容区域 -->
    <view class="task-content bg-white margin-top-sm">
      <!-- 全部任务 -->
      <view v-if="currentTab === 'all'" class="task-section">
        <view v-if="allTasks.length === 0 && !loading" class="empty-state">
          <text class="cuIcon-list empty-icon"></text>
          <text class="empty-text">暂无任务</text>
        </view>
        <scroll-view
          v-else
          scroll-y
          class="task-list"
          :refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @scrolltolower="loadMore"
        >
          <view
            v-for="task in allTasks"
            :key="task.id"
            :class="['task-card', task.statusStyleClass]"
            @tap="viewTaskDetail(task.id)"
          >
            <view class="card-header">
              <view :class="['work-type-tag', task.statusStyleClass]">
                {{ task.workTypeName }}
              </view>
            </view>
            <view class="card-content">
              <view class="task-name">{{
                task.productName || task.taskName || "未知产品"
              }}</view>
              <view class="task-details">
                <view class="detail-row">
                  <text class="detail-label">订单编号:</text>
                  <text class="detail-text">{{ task.orderNo || "-" }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">产品信息:</text>
                  <text class="detail-text">{{
                    task.productInfo || task.productSpec || "-"
                  }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务状态:</text>
                  <text class="detail-text">{{ task.statusText }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务数量:</text>
                  <text class="detail-text"
                    >{{ task.completedQuantity || 0 }}/{{
                      task.taskQuantity || 0
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">协作类型:</text>
                  <text
                    :class="[
                      'detail-text',
                      'collaboration-tag',
                      task.collaborationTypeClass,
                    ]"
                    >{{ task.collaborationTypeText }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">参与人数:</text>
                  <text class="detail-text"
                    >{{ task.currentParticipants || 0 }}/{{
                      task.maxParticipants || 1
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">部分领取:</text>
                  <text
                    :class="[
                      'detail-text',
                      'partial-claim-tag',
                      task.allowPartialClaimClass,
                    ]"
                    >{{ task.allowPartialClaimText }}</text
                  >
                </view>
                <view class="detail-row" v-if="task.planStartDate">
                  <text class="detail-label">计划开始:</text>
                  <text class="detail-text">{{
                    formatDate(task.planStartDate)
                  }}</text>
                </view>
              </view>
            </view>
            <view class="card-footer">
              <view :class="['status-indicator', task.statusClass]"></view>
              <view class="task-actions" @tap.stop="">
                <button
                  v-if="canClaimTask(task)"
                  class="action-btn primary"
                  @tap="claimTask(task.id)"
                >
                  领取
                </button>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 可领取任务 -->
      <view v-else-if="currentTab === 'available'" class="task-section">
        <view
          v-if="availableTasks.length === 0 && !loading"
          class="empty-state"
        >
          <text class="cuIcon-task empty-icon"></text>
          <text class="empty-text">暂无可领取任务</text>
        </view>
        <scroll-view
          v-else
          scroll-y
          class="task-list"
          :refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @scrolltolower="loadMore"
        >
          <view
            v-for="task in availableTasks"
            :key="task.id"
            :class="['task-card', task.statusStyleClass]"
            @tap="viewTaskDetail(task.id)"
          >
            <view class="card-header">
              <view
                :class="[
                  'work-type-tag',
                  task.statusStyleClass,
                  getTaskClaimStatusClass(task),
                ]"
              >
                {{ task.workTypeName }}
              </view>
            </view>
            <view class="card-content">
              <view class="task-name">{{
                task.productName || task.taskName || "未知产品"
              }}</view>
              <view class="task-details">
                <view class="detail-row">
                  <text class="detail-label">订单编号:</text>
                  <text class="detail-text">{{ task.orderNo || "-" }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">产品信息:</text>
                  <text class="detail-text">{{
                    task.productInfo || task.productSpec || "-"
                  }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务状态:</text>
                  <text class="detail-text">{{ task.statusText }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务数量:</text>
                  <text class="detail-text"
                    >{{ task.completedQuantity || 0 }}/{{
                      task.taskQuantity || 0
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">协作类型:</text>
                  <text
                    :class="[
                      'detail-text',
                      'collaboration-tag',
                      task.collaborationTypeClass,
                    ]"
                    >{{ task.collaborationTypeText }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">参与人数:</text>
                  <text class="detail-text"
                    >{{ task.currentParticipants || 0 }}/{{
                      task.maxParticipants || 1
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">部分领取:</text>
                  <text
                    :class="[
                      'detail-text',
                      'partial-claim-tag',
                      task.allowPartialClaimClass,
                    ]"
                    >{{ task.allowPartialClaimText }}</text
                  >
                </view>
                <view class="detail-row" v-if="task.planStartDate">
                  <text class="detail-label">计划开始:</text>
                  <text class="detail-text">{{
                    formatDate(task.planStartDate)
                  }}</text>
                </view>
              </view>
            </view>
            <view class="card-footer">
              <view :class="['status-indicator', task.statusClass]"></view>
              <view class="task-actions" @tap.stop="">
                <button
                  v-if="canClaimTask(task)"
                  class="action-btn primary"
                  @tap="claimTask(task.id)"
                >
                  领取
                </button>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 我的任务 -->
      <view v-else-if="currentTab === 'my'" class="task-section">
        <!-- 多选操作栏 -->
        <view v-if="myTasks.length > 0" class="multi-select-bar">
          <view class="select-actions">
            <!-- <button
              class="cu-btn"
              :class="isMultiSelectMode ? 'bg-gray' : 'line-blue'"
              @tap="toggleMultiSelectMode"
            >
              {{ isMultiSelectMode ? "取消" : "完成" }}
            </button> -->

            <button
              class="cu-btn line-blue margin-left-sm"
              @tap="toggleMultiSelectMode"
            >
              完成
            </button>
            <button
              class="cu-btn line-orange margin-left-sm"
              @tap="toggleWithdrawMode"
            >
              撤回
            </button>
            <view v-if="isMultiSelectMode" class="multi-select-toolbar">
              <view class="selected-count">
                已选择
                <text class="count-number">{{ selectedTasks.length }}</text>
                个任务
              </view>
              <view class="toolbar-actions">
                <button @click="exitMultiSelect" class="toolbar-btn cancel">
                  取消
                </button>
                <button
                  @click="openBatchCompleteModal"
                  class="toolbar-btn primary"
                  :disabled="selectedTasks.length === 0"
                >
                  批量完成
                </button>
              </view>
            </view>
            <view v-if="isWithdrawMode" class="multi-select-toolbar">
              <view class="selected-count">
                已选择
                <text class="count-number">{{ selectedTasks.length }}</text>
                个任务
              </view>
              <view class="toolbar-actions">
                <button @click="exitWithdrawMode" class="toolbar-btn cancel">
                  取消
                </button>
                <button
                  @click="confirmWithdrawTasks"
                  class="toolbar-btn warning"
                  :disabled="selectedTasks.length === 0"
                >
                  确认撤回
                </button>
              </view>
            </view>
          </view>
        </view>

        <view v-if="myTasks.length === 0 && !loading" class="empty-state">
          <text class="cuIcon-calendar empty-icon"></text>
          <text class="empty-text">暂无进行中任务</text>
        </view>
        <scroll-view
          v-else
          scroll-y
          class="task-list"
          :refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @scrolltolower="loadMore"
        >
          <view
            v-for="task in myTasks"
            :key="task.id"
            :class="[
              'task-card',
              task.statusStyleClass,
              {
                selected: isTaskSelected(task),
                'multi-select-mode': isMultiSelectMode || isWithdrawMode,
              },
            ]"
            @tap="handleTaskTap(task)"
          >
            <view class="card-header">
              <view class="header-left">
                <view
                  v-if="isMultiSelectMode || isWithdrawMode"
                  class="select-checkbox"
                  :class="{ checked: isTaskSelected(task) }"
                  @tap.stop="toggleTaskSelection(task)"
                >
                  <text v-if="isTaskSelected(task)" class="cuIcon-check"></text>
                </view>
                <view
                  :class="[
                    'work-type-tag',
                    task.workTypeClass,
                    getTaskClaimStatusClass(task),
                  ]"
                >
                  {{ task.workTypeName }}
                </view>
              </view>
            </view>
            <view class="card-content">
              <view class="task-name">{{
                task.productName || task.taskName || "未知产品"
              }}</view>
              <view class="task-details">
                <view class="detail-row">
                  <text class="detail-label">订单编号:</text>
                  <text class="detail-text">{{ task.orderNo || "-" }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">产品信息:</text>
                  <text class="detail-text">{{
                    task.productInfo || task.productSpec || "-"
                  }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务状态:</text>
                  <text class="detail-text">{{ task.statusText }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务数量:</text>
                  <text class="detail-text"
                    >{{ task.completedQuantity || 0 }}/{{
                      task.taskQuantity || 0
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">协作类型:</text>
                  <text
                    :class="[
                      'detail-text',
                      'collaboration-tag',
                      task.collaborationTypeClass,
                    ]"
                    >{{ task.collaborationTypeText }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">参与人数:</text>
                  <text class="detail-text"
                    >{{ task.currentParticipants || 0 }}/{{
                      task.maxParticipants || 1
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">部分领取:</text>
                  <text
                    :class="[
                      'detail-text',
                      'partial-claim-tag',
                      task.allowPartialClaimClass,
                    ]"
                    >{{ task.allowPartialClaimText }}</text
                  >
                </view>
                <view class="detail-row" v-if="task.planStartDate">
                  <text class="detail-label">计划开始:</text>
                  <text class="detail-text">{{
                    formatDate(task.planStartDate)
                  }}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 历史任务 -->
      <view v-else-if="currentTab === 'history'" class="task-section">
        <view v-if="historyTasks.length === 0 && !loading" class="empty-state">
          <text class="cuIcon-time empty-icon"></text>
          <text class="empty-text">暂无历史任务</text>
        </view>
        <scroll-view
          v-else
          scroll-y
          class="task-list"
          :refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @scrolltolower="loadMore"
        >
          <view
            v-for="task in historyTasks"
            :key="task.id"
            :class="['task-card', task.statusStyleClass]"
            @tap="viewTaskDetail(task.id)"
          >
            <view class="card-header">
              <view
                :class="[
                  'work-type-tag',
                  task.statusStyleClass,
                  getTaskClaimStatusClass(task),
                ]"
              >
                {{ task.workTypeName }}
              </view>
            </view>
            <view class="card-content">
              <view class="task-name">{{
                task.productName || task.taskName || "未知产品"
              }}</view>
              <view class="task-details">
                <view class="detail-row">
                  <text class="detail-label">订单编号:</text>
                  <text class="detail-text">{{ task.orderNo || "-" }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">产品信息:</text>
                  <text class="detail-text">{{
                    task.productInfo || task.productSpec || "-"
                  }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务状态:</text>
                  <text class="detail-text">{{ task.statusText }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">任务数量:</text>
                  <text class="detail-text"
                    >{{ task.completedQuantity || 0 }}/{{
                      task.taskQuantity || 0
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">协作类型:</text>
                  <text
                    :class="[
                      'detail-text',
                      'collaboration-tag',
                      task.collaborationTypeClass,
                    ]"
                    >{{ task.collaborationTypeText }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">参与人数:</text>
                  <text class="detail-text"
                    >{{ task.currentParticipants || 0 }}/{{
                      task.maxParticipants || 1
                    }}</text
                  >
                </view>
                <view class="detail-row">
                  <text class="detail-label">部分领取:</text>
                  <text
                    :class="[
                      'detail-text',
                      'partial-claim-tag',
                      task.allowPartialClaimClass,
                    ]"
                    >{{ task.allowPartialClaimText }}</text
                  >
                </view>
                <view class="detail-row" v-if="task.planStartDate">
                  <text class="detail-label">计划开始:</text>
                  <text class="detail-text">{{
                    formatDate(task.planStartDate)
                  }}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="cuIcon-loading2 cuIconfont-spin text-blue"></text>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 批量完成任务模态框 -->
    <view v-if="showBatchCompleteModal" class="cu-modal show">
      <view class="cu-dialog batch-complete-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">批量完成任务</view>
          <view class="action">
            <text
              class="cuIcon-close text-red"
              @tap="closeBatchCompleteModal"
            ></text>
          </view>
        </view>
        <scroll-view scroll-y class="batch-complete-content">
          <view
            v-for="task in batchCompleteTasks"
            :key="task.id"
            class="batch-task-item"
          >
            <view class="task-info">
              <view class="task-title">{{
                task.productName || task.taskName
              }}</view>
            </view>
            <view class="task-info">
              <view class="task-title">{{ task.workTypeName }}</view>
            </view>
            <view class="completion-form">
              <view class="form-row">
                <text class="form-label">完成数量:</text>
                <input
                  v-model.number="task.completedQuantity"
                  type="number"
                  :placeholder="`默认: ${task.taskQuantity}`"
                  class="form-input"
                />
                <text class="form-unit">/ {{ task.taskQuantity }}</text>
              </view>
              <view class="form-row">
                <text class="form-label">备注:</text>
                <input
                  v-model="task.remark"
                  placeholder="完成情况说明（可选）"
                  class="form-input full-width"
                />
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="cu-bar bg-white">
          <view class="action">
            <button
              class="cu-btn bg-gray margin-right"
              @tap="closeBatchCompleteModal"
            >
              取消
            </button>
            <button class="cu-btn bg-green" @tap="submitBatchComplete">
              确认完成
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import productionTask from "@/api/mes/productionTask";
import authService from "@/common/auth/authService";
import { USER_INFO } from "@/common/util/constants";

export default {
  data() {
    return {
      // 生产计划ID
      planId: null,
      // 当前选中的标签页
      currentTab: "all",
      // 标签页配置
      taskTabs: [
        { key: "all", label: "全部任务", count: 0 },
        { key: "available", label: "可领取任务", count: 0 },
        { key: "my", label: "我的任务", count: 0 },
        { key: "history", label: "历史任务", count: 0 },
      ],
      // 各标签页的任务数据
      allTasks: [],
      availableTasks: [],
      myTasks: [],
      historyTasks: [],
      // 搜索相关
      showSearch: false,
      searchKeyword: "",
      searchTimer: null,
      // 分页配置
      pageSize: 20,
      pagination: {
        all: { current: 1, hasMore: true, total: 0 },
        available: { current: 1, hasMore: true, total: 0 },
        my: { current: 1, hasMore: true, total: 0 },
        history: { current: 1, hasMore: true, total: 0 },
      },
      // 状态控制
      loading: false,
      refreshing: false,
      // 多选相关
      isMultiSelectMode: false,
      isWithdrawMode: false,
      selectedTasks: [],
      // 筛选相关
      showFilterModal: false,
      // 批量完成任务模态框
      showBatchCompleteModal: false,
      batchCompleteTasks: [],
      filterParams: {
        status: "",
        workType: "",
        dateRange: "",
        startDate: "",
        endDate: "",
      },
      statusOptions: [
        { label: "全部", value: "" },
        { label: "待领取", value: "0" },
        { label: "已领取", value: "1" },
        { label: "进行中", value: "2" },
        { label: "已完成", value: "3" },
        { label: "暂停", value: "4" },
      ],
      priorityOptions: [
        { label: "全部", value: "" },
        { label: "高优先级", value: "high" },
        { label: "中优先级", value: "medium" },
        { label: "低优先级", value: "low" },
      ],
      workTypeOptions: [{ label: "全部", value: "" }],
      dateRangeOptions: [
        { label: "全部", value: "" },
        { label: "今天", value: "today" },
        { label: "本周", value: "week" },
        { label: "本月", value: "month" },
        { label: "最近3个月", value: "quarter" },
        { label: "自定义", value: "custom" },
      ],
    };
  },
  onLoad(options) {
    // 接收从生产计划页面传递的planId
    if (options.planId) {
      this.planId = options.planId;
    }
    this.initPage();
    this.loadWorkTypes();
  },
  onShow() {
    this.refreshCurrentTab();
  },
  methods: {
    // 初始化页面
    async initPage() {
      await this.loadTasksByTab(this.currentTab, true);
      this.updateTabCounts();
    },

    // 加载工种类型
    async loadWorkTypes() {
      try {
        const response = await this.$http.get("/mes/worktype/all");
        if (response.data.success) {
          const workTypes = response.data.result || [];
          this.workTypeOptions = [
            { label: "全部", value: "" },
            ...workTypes.map((item) => ({
              label: item.workTypeName,
              value: item.id,
            })),
          ];
        }
      } catch (error) {
        console.error("加载工种类型失败:", error);
      }
    },

    // 开始时间选择
    onStartDateChange(e) {
      this.filterParams.startDate = e.detail.value;
    },

    // 结束时间选择
    onEndDateChange(e) {
      this.filterParams.endDate = e.detail.value;
    },

    // 切换标签页
    async switchTab(tabKey) {
      if (this.currentTab === tabKey) return;
      this.currentTab = tabKey;
      await this.loadTasksByTab(tabKey, true);
      this.updateTabCounts();
    },

    // 根据标签页加载任务数据
    async loadTasksByTab(tabKey, isRefresh = false) {
      const pagination = this.pagination[tabKey];
      if (isRefresh) {
        pagination.current = 1;
        pagination.hasMore = true;
      }
      if (!pagination.hasMore && !isRefresh) return;

      try {
        this.loading = true;
        const userInfo =
          authService.getUserInfo() || uni.getStorageSync(USER_INFO);
        if (!userInfo) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        let apiMethod, params;
        const baseParams = {
          pageNo: pagination.current,
          pageSize: this.pageSize,
          keyword: this.searchKeyword,
          // 添加筛选参数 - 使用正确的字段名
          status: this.filterParams.status,
          priority: this.filterParams.priority,
          workTypeId: this.filterParams.workType, // 使用正确的字段名
          dateRange: this.filterParams.dateRange,
        };

        switch (tabKey) {
          case "all":
            apiMethod = productionTask.getAllTasks;
            params = {
              ...baseParams,
              planId: this.planId,
            };
            break;
          case "available":
            apiMethod = productionTask.getAvailableTasks;
            params = {
              ...baseParams,
              employeeId: userInfo.id,
              planId: this.planId,
            };
            break;
          case "my":
            apiMethod = productionTask.getMyTasks;
            params = {
              ...baseParams,
              employeeId: userInfo.id,
              planId: this.planId,
            };
            break;
          case "history":
            apiMethod = productionTask.getHistoryTasks;
            params = {
              ...baseParams,
              employeeId: userInfo.id,
              planId: this.planId,
            };
            break;
          default:
            return;
        }

        let newData = [];
        try {
          const res = await apiMethod(params);
          console.log("API响应:", res);

          const response = res.data || res;
          console.log("响应数据:", response);

          newData =
            response.result?.records ||
            response.data ||
            response.records ||
            response.list ||
            [];

          // 提取总数量
          const totalCount =
            response.result?.total || response.total || response.count || 0;

          // 存储总数量到分页对象
          pagination.total = totalCount;

          // 确保 newData 是数组
          if (!Array.isArray(newData)) {
            console.warn("API返回的数据不是数组格式:", newData);
            console.warn("完整响应结构:", response);
            newData = [];
          }
        } catch (apiError) {
          console.warn("API调用失败，使用模拟数据:", apiError);
          // 使用模拟数据进行测试
          newData = this.getMockData(tabKey, pagination.current);
        }

        // 数据预处理 - 遵循UniApp数据驱动原则，适配真实API字段
        const processedData = newData.map((item) => ({
          ...item,
          statusClass: this.calculateStatusClass(item.status),
          statusText: this.calculateStatusText(item.status),
          priorityText: this.calculatePriorityText(item.priority),
          statusStyleClass: this.calculateStatusClass(item.status), // 用于卡片边框颜色
          claimStatusClass: this.getTaskClaimStatusClass(item),
          taskName: item.productName || item.taskName || "未知任务",
          completedTime: this.formatDateTime(
            item.actualEndDate || item.completedTime
          ),
          estimatedHours: item.estimatedHours || 0,
          usedHours: item.actualHours || item.usedHours || 0,
          totalHours: item.actualHours || item.totalHours || 0,
          progress:
            item.completedQuantity && item.taskQuantity
              ? Math.round((item.completedQuantity / item.taskQuantity) * 100)
              : 0,
          taskCode: item.orderNo
            ? `${item.orderNo}-${item.sequence}`
            : `T${String(item.id).slice(-3)}`,
          // 协作相关字段预处理
          collaborationTypeText: this.calculateCollaborationTypeText(
            item.collaborationType
          ),
          collaborationTypeClass: this.calculateCollaborationTypeClass(
            item.collaborationType
          ),
          allowPartialClaimText: this.calculateAllowPartialClaimText(
            item.allowPartialClaim
          ),
          allowPartialClaimClass: this.calculateAllowPartialClaimClass(
            item.allowPartialClaim
          ),
        }));

        if (isRefresh) {
          this[`${tabKey}Tasks`] = processedData;
        } else {
          this[`${tabKey}Tasks`] = [
            ...this[`${tabKey}Tasks`],
            ...processedData,
          ];
        }

        pagination.hasMore = newData.length >= this.pageSize;
        pagination.current++;
      } catch (error) {
        console.error("加载任务失败:", error);
        uni.showToast({ title: "加载失败", icon: "none" });
      } finally {
        this.loading = false;
        this.refreshing = false;
      }
    },

    // 计算状态样式类
    calculateStatusClass(status) {
      const statusMap = {
        0: "status-pending", // 待领取
        1: "status-assigned", // 已领取
        2: "status-progress", // 进行中
        3: "status-completed", // 已完成
        4: "status-paused", // 暂停
        // 兼容字符串状态
        pending: "status-pending",
        assigned: "status-assigned",
        in_progress: "status-progress",
        paused: "status-paused",
        completed: "status-completed",
        cancelled: "status-cancelled",
      };
      return statusMap[status] || "status-default";
    },

    // 计算状态文本
    calculateStatusText(status) {
      const statusMap = {
        0: "待领取",
        1: "已领取",
        2: "进行中",
        3: "已完成",
        4: "已暂停",
        // 兼容字符串状态
        pending: "待领取",
        assigned: "已领取",
        in_progress: "进行中",
        paused: "已暂停",
        completed: "已完成",
        cancelled: "已取消",
      };
      return statusMap[status] || "未知";
    },

    // 计算优先级文本
    calculatePriorityText(priority) {
      const priorityMap = {
        high: "高",
        medium: "中",
        low: "低",
      };
      return priorityMap[priority] || "中";
    },

    // 计算协作类型文本
    calculateCollaborationTypeText(collaborationType) {
      const typeMap = {
        0: "独立完成",
        1: "协作完成",
        2: "分段完成",
      };
      return typeMap[collaborationType] || "独立完成";
    },

    // 计算协作类型样式类
    calculateCollaborationTypeClass(collaborationType) {
      const classMap = {
        0: "collaboration-independent", // 绿色
        1: "collaboration-cooperative", // 蓝色
        2: "collaboration-segmented", // 橙色
      };
      return classMap[collaborationType] || "collaboration-independent";
    },

    // 计算部分领取文本
    calculateAllowPartialClaimText(allowPartialClaim) {
      return allowPartialClaim === 1 ? "是" : "否";
    },

    // 计算部分领取样式类
    calculateAllowPartialClaimClass(allowPartialClaim) {
      return allowPartialClaim === 1 ? "partial-claim-yes" : "partial-claim-no";
    },

    // 检查任务是否可以领取
    canClaimTask(task) {
      const userInfo =
        authService.getUserInfo() || uni.getStorageSync(USER_INFO);
      const currentUserId = userInfo?.id;

      if (!currentUserId) {
        return false;
      }

      // 任务已完成不能领取
      if (task.status === 3 || task.status === "completed") {
        return false;
      }

      // 检查当前用户是否已参与该任务
      const userParticipated =
        task.participants &&
        task.participants.some((p) => p.employeeId === currentUserId);

      // 多人协作类型 (cooperative, segmented)
      if (
        task.collaborationType === "cooperative" ||
        task.collaborationType === "segmented"
      ) {
        // 多人协作：任务没有完成且当前用户没有领取
        return !userParticipated;
      } else {
        // 独立完成类型 (independent)
        // 独立完成：任务没有完成且没有任何人领取
        const hasAnyParticipants =
          task.participants && task.participants.length > 0;
        return !hasAnyParticipants;
      }
    },

    // 获取任务领取状态样式类
    getTaskClaimStatusClass(task) {
      const userInfo =
        authService.getUserInfo() || uni.getStorageSync(USER_INFO);
      const currentUserId = userInfo?.id;

      // 未领取状态 (0-待领取)
      if (task.status === 0 || task.status === "pending") {
        return "claim-status-unclaimed";
      }

      // 当前用户领取的任务 - 通过参与者信息判断
      if (
        task.participants &&
        task.participants.some((p) => p.employeeId === currentUserId)
      ) {
        return "claim-status-my-task";
      }

      // 其他用户领取的任务 (1-已领取, 2-进行中, 4-暂停)
      if (
        task.status === 1 ||
        task.status === 2 ||
        task.status === 4 ||
        task.status === "assigned" ||
        task.status === "in_progress" ||
        task.status === "paused"
      ) {
        return "claim-status-others";
      }

      // 默认状态
      return "claim-status-default";
    },

    // 切换多选模式
    toggleMultiSelectMode() {
      this.isMultiSelectMode = !this.isMultiSelectMode;
      if (!this.isMultiSelectMode) {
        this.selectedTasks = [];
      }
    },

    // 退出多选模式
    exitMultiSelect() {
      this.isMultiSelectMode = false;
      this.selectedTasks = [];
    },

    // 切换撤回模式
    toggleWithdrawMode() {
      this.isWithdrawMode = !this.isWithdrawMode;
      if (!this.isWithdrawMode) {
        this.selectedTasks = [];
      }
      // 确保只有一种模式激活
      if (this.isWithdrawMode) {
        this.isMultiSelectMode = false;
      }
    },

    // 退出撤回模式
    exitWithdrawMode() {
      this.isWithdrawMode = false;
      this.selectedTasks = [];
    },

    // 确认撤回任务
    async confirmWithdrawTasks() {
      if (this.selectedTasks.length === 0) {
        uni.showToast({ title: "请先选择要撤回的任务", icon: "none" });
        return;
      }

      try {
        uni.showModal({
          title: "确认撤回",
          content: `确定要撤回选中的 ${this.selectedTasks.length} 个任务吗？撤回后任务将变为未领取状态。`,
          success: async (res) => {
            if (res.confirm) {
              await this.withdrawTasks();
            }
          },
        });
      } catch (error) {
        console.error("撤回任务确认失败:", error);
      }
    },

    // 执行撤回任务
    async withdrawTasks() {
      try {
        const userInfo =
          authService.getUserInfo() || uni.getStorageSync(USER_INFO);
        if (!userInfo) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        const taskIds = this.selectedTasks.map((task) => task.id);

        await productionTask.withdrawTasks({
          taskIds: taskIds,
          employeeId: userInfo.id,
        });

        uni.showToast({ title: "撤回成功", icon: "success" });

        // 退出撤回模式并刷新数据
        this.exitWithdrawMode();
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("available", true),
          this.loadTasksByTab("my", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("撤回任务失败:", error);
        uni.showToast({ title: "撤回失败", icon: "none" });
      }
    },

    // 切换任务选中状态
    toggleTaskSelection(task) {
      if (!this.isMultiSelectMode && !this.isWithdrawMode) return;

      const index = this.selectedTasks.findIndex((t) => t.id === task.id);
      if (index > -1) {
        this.selectedTasks.splice(index, 1);
      } else {
        this.selectedTasks.push(task);
      }
    },

    // 检查任务是否被选中
    isTaskSelected(task) {
      return this.selectedTasks.some((t) => t.id === task.id);
    },

    // 打开批量完成模态框
    openBatchCompleteModal() {
      if (this.selectedTasks.length === 0) {
        uni.showToast({ title: "请先选择任务", icon: "none" });
        return;
      }

      // 初始化批量完成任务数据
      this.batchCompleteTasks = this.selectedTasks.map((task) => ({
        ...task,
        completedQuantity: task.taskQuantity || 0,
        remark: "",
      }));

      this.showBatchCompleteModal = true;
    },

    // 关闭批量完成模态框
    closeBatchCompleteModal() {
      this.showBatchCompleteModal = false;
      this.batchCompleteTasks = [];
    },

    // 提交批量完成
    async submitBatchComplete() {
      try {
        const userInfo =
          authService.getUserInfo() || uni.getStorageSync(USER_INFO);
        if (!userInfo) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        // 验证数据
        for (const task of this.batchCompleteTasks) {
          if (!task.completedQuantity || task.completedQuantity <= 0) {
            uni.showToast({
              title: `请输入${task.productName || task.taskName}的完成数量`,
              icon: "none",
            });
            return;
          }
        }

        // 构建批量完成请求数据
        const batchCompleteData = {
          employeeId: userInfo.id,
          tasks: this.batchCompleteTasks.map((task) => ({
            taskId: task.id,
            completedQuantity: task.completedQuantity,
            remark: task.remark || "",
          })),
        };

        // 调用批量完成接口
        await productionTask.batchCompleteTask(batchCompleteData);

        uni.showToast({ title: "批量完成成功", icon: "success" });

        // 关闭模态框并刷新数据
        this.closeBatchCompleteModal();
        this.isMultiSelectMode = false;
        this.selectedTasks = [];

        // 刷新相关标签页
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("my", true),
          this.loadTasksByTab("history", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("批量完成任务失败:", error);
        uni.showToast({ title: "批量完成失败", icon: "none" });
      }
    },

    // 处理任务点击事件
    handleTaskTap(task) {
      if (this.isMultiSelectMode || this.isWithdrawMode) {
        // 多选模式或撤回模式下切换选中状态
        this.toggleTaskSelection(task);
      }
    },

    // 显示任务操作菜单
    showTaskActions(task) {
      const actions = [];
      const userInfo =
        authService.getUserInfo() || uni.getStorageSync(USER_INFO);
      const currentUserId = userInfo?.id;

      // 检查当前用户是否参与了该任务
      const userParticipated =
        task.participants &&
        task.participants.some((p) => p.employeeId === currentUserId);

      // 根据任务状态和用户权限添加可用操作
      if (this.canClaimTask(task)) {
        // 可领取状态
        actions.push("领取任务");
      } else if (
        (task.status === 1 || task.status === "assigned") &&
        userParticipated
      ) {
        // 已领取状态，且当前用户参与了该任务
        actions.push("提交任务");
      } else if (
        (task.status === 2 || task.status === "in_progress") &&
        userParticipated
      ) {
        // 进行中状态，且当前用户参与了该任务
        actions.push("暂停任务", "完成任务", "更新进度");
      } else if (
        (task.status === 4 || task.status === "paused") &&
        userParticipated
      ) {
        // 暂停状态，且当前用户参与了该任务
        actions.push("恢复任务");
      }

      actions.push("查看详情");

      uni.showActionSheet({
        itemList: actions,
        success: (res) => {
          const action = actions[res.tapIndex];
          switch (action) {
            case "领取任务":
              this.claimTask(task.id);
              break;
            case "提交任务":
              this.submitTask(task.id);
              break;
            case "暂停任务":
              this.pauseTask(task.id);
              break;
            case "恢复任务":
              this.resumeTask(task.id);
              break;
            case "完成任务":
              this.showCompleteModal(task);
              break;
            case "更新进度":
              this.showProgressModal(task);
              break;
            case "查看详情":
              this.showTaskDetail(task);
              break;
          }
        },
      });
    },

    // 显示任务详情
    showTaskDetail(task) {
      // 这里可以跳转到详情页面或显示详情模态框
      uni.showModal({
        title: "任务详情",
        content: `任务编号: ${task.id}\n工种: ${task.workTypeName}\n数量: ${
          task.completedQuantity || 0
        }/${task.taskQuantity}\n状态: ${task.statusText}`,
        showCancel: false,
      });
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return "";
      const date = new Date(dateTime);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(d.getDate()).padStart(2, "0")}`;
    },

    // 更新标签页计数
    updateTabCounts() {
      this.taskTabs.forEach((tab) => {
        switch (tab.key) {
          case "all":
            tab.count = this.pagination.all.total || this.allTasks.length;
            break;
          case "available":
            tab.count =
              this.pagination.available.total || this.availableTasks.length;
            break;
          case "my":
            tab.count = this.pagination.my.total || this.myTasks.length;
            break;
          case "history":
            tab.count =
              this.pagination.history.total || this.historyTasks.length;
            break;
        }
      });
    },

    // 搜索功能
    onSearch() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.loadTasksByTab(this.currentTab, true);
      }, 300);
    },

    // 下拉刷新
    async onRefresh() {
      this.refreshing = true;
      await this.loadTasksByTab(this.currentTab, true);
      this.updateTabCounts();
    },

    // 加载更多
    async loadMore() {
      await this.loadTasksByTab(this.currentTab, false);
    },

    // 刷新当前标签页
    async refreshCurrentTab() {
      await this.loadTasksByTab(this.currentTab, true);
      this.updateTabCounts();
    },

    // 任务操作方法
    async claimTask(taskId) {
      try {
        const userInfo =
          authService.getUserInfo() || uni.getStorageSync(USER_INFO);
        if (!userInfo) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        await productionTask.claimTask({
          taskId: taskId,
          employeeId: userInfo.id,
          remark: "",
        });
        uni.showToast({ title: "领取成功", icon: "success" });
        // 刷新相关标签页
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("available", true),
          this.loadTasksByTab("my", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("领取任务失败:", error);
        uni.showToast({ title: "领取失败", icon: "none" });
      }
    },

    async submitTask(taskId) {
      try {
        const userInfo =
          authService.getUserInfo() || uni.getStorageSync(USER_INFO);
        if (!userInfo) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        await productionTask.submitTask({
          taskId: taskId,
          employeeId: userInfo.id,
        });
        uni.showToast({ title: "提交成功", icon: "success" });
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("my", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("提交任务失败:", error);
        uni.showToast({ title: "提交失败", icon: "none" });
      }
    },

    async pauseTask(taskId) {
      try {
        await productionTask.pauseTask({ taskId });
        uni.showToast({ title: "暂停成功", icon: "success" });
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("my", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("暂停任务失败:", error);
        uni.showToast({ title: "暂停失败", icon: "none" });
      }
    },

    async resumeTask(taskId) {
      try {
        await productionTask.resumeTask({ taskId });
        uni.showToast({ title: "恢复成功", icon: "success" });
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("my", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("恢复任务失败:", error);
        uni.showToast({ title: "恢复失败", icon: "none" });
      }
    },

    // 显示完成任务模态框
    showCompleteModal(task) {
      // 这里应该显示一个完成任务的模态框，包含完成数量输入
      // 暂时使用简单的完成操作
      this.completeTask(task.id);
    },

    async completeTask(taskId) {
      try {
        await productionTask.completeTask({ taskId });
        uni.showToast({ title: "完成成功", icon: "success" });
        await Promise.all([
          this.loadTasksByTab("all", true),
          this.loadTasksByTab("my", true),
          this.loadTasksByTab("history", true),
        ]);
        this.updateTabCounts();
      } catch (error) {
        console.error("完成任务失败:", error);
        uni.showToast({ title: "完成失败", icon: "none" });
      }
    },

    // 查看任务详情
    viewTaskDetail(taskId) {
      uni.navigateTo({
        url: `/pages/production/task/detail?id=${taskId}`,
      });
    },

    // 打开筛选弹窗
    openFilterModal() {
      this.showFilterModal = true;
    },

    // 关闭筛选弹窗
    closeFilterModal() {
      this.showFilterModal = false;
    },

    // 筛选器相关方法
    selectFilter(type, value) {
      this.filterParams[type] = this.filterParams[type] === value ? "" : value;
    },

    resetFilter() {
      this.filterParams = {
        status: "",
        priority: "",
        workType: "",
        dateRange: "",
        startDate: "",
        endDate: "",
      };
    },

    async applyFilter() {
      this.closeFilterModal();
      // 重新加载当前标签页数据
      await this.loadTasksByTab(this.currentTab, true);
      this.updateTabCounts();
      uni.showToast({
        title: "筛选已应用",
        icon: "success",
      });
    },

    // 获取模拟数据（用于API不可用时的测试）
    getMockData(tabKey, pageNo) {
      const mockTasks = [
        {
          id: "1",
          taskName: "铝合金门窗切割任务",
          workTypeName: "切割",
          status: "pending",
          priority: "high",
          estimatedHours: 4,
          usedHours: 0,
          progress: 0,
          completedTime: null,
          totalHours: 0,
        },
        {
          id: "2",
          taskName: "窗框组装任务",
          workTypeName: "组装",
          status: "assigned",
          priority: "medium",
          estimatedHours: 6,
          usedHours: 2,
          progress: 30,
          completedTime: null,
          totalHours: 0,
        },
        {
          id: "3",
          taskName: "玻璃安装任务",
          workTypeName: "安装",
          status: "in_progress",
          priority: "high",
          estimatedHours: 3,
          usedHours: 1.5,
          progress: 50,
          completedTime: null,
          totalHours: 0,
        },
        {
          id: "4",
          taskName: "质量检测任务",
          workTypeName: "检测",
          status: "completed",
          priority: "low",
          estimatedHours: 2,
          usedHours: 2,
          progress: 100,
          completedTime: "2024-08-31 10:30:00",
          totalHours: 2,
        },
      ];

      // 根据标签页过滤数据
      let filteredTasks = [];
      switch (tabKey) {
        case "all":
          filteredTasks = mockTasks;
          break;
        case "available":
          filteredTasks = mockTasks.filter((task) => task.status === "pending");
          break;
        case "my":
          filteredTasks = mockTasks.filter((task) =>
            ["assigned", "in_progress", "paused"].includes(task.status)
          );
          break;
        case "history":
          filteredTasks = mockTasks.filter(
            (task) => task.status === "completed"
          );
          break;
        default:
          filteredTasks = [];
      }

      // 模拟分页
      const startIndex = (pageNo - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return filteredTasks.slice(startIndex, endIndex);
    },
  },
};
</script>

<style lang="scss">
.production-task-container {
  height: 100vh;
  background-color: #f5f5f5;
}

/* 自定义日期范围样式 */
.custom-date-range {
  margin-top: 20rpx;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
}

.date-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.date-input-group:last-child {
  margin-bottom: 0;
}

.date-label {
  width: 120rpx;
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.date-picker {
  flex: 1;
  padding: 20rpx;
  background: white;
  border-radius: 8rpx;
  border: 1px solid #e0e0e0;
  font-size: 28rpx;
  color: #333;
  text-align: center;
}

/* 导航栏样式 */
.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: white;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  transition: all 0.3s ease;

  &:active {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0.95);
  }
}

.filter-text {
  font-size: 24rpx;
  color: white;
  font-weight: 500;
}

/* 标签页样式 */
.task-tabs {
  padding: 20rpx;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.tab-scroll {
  white-space: nowrap;
}

.tab-list {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 0 10rpx;
}

.tab-item {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 16rpx 24rpx;
  background: #f8f9fa;
  border-radius: 50rpx;
  transition: all 0.3s ease;
  white-space: nowrap;
  flex-shrink: 0;

  &.active {
    background: linear-gradient(135deg, #007aff, #5ac8fa);
    color: white;
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
  }
}

.tab-text {
  font-size: 28rpx;
  font-weight: 500;
}

.tab-badge {
  min-width: 36rpx;
  height: 36rpx;
  line-height: 36rpx;
  text-align: center;
  background: #ff3b30;
  color: white;
  border-radius: 18rpx;
  font-size: 22rpx;
  font-weight: bold;

  .tab-item.active & {
    background: rgba(255, 255, 255, 0.3);
    color: white;
  }
}

/* 搜索栏样式 */
.search-section {
  border-radius: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-wrapper {
  padding: 20rpx;
}

.search-input-box {
  position: relative;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 50rpx;
  padding: 0 40rpx 0 20rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;

  &:focus-within {
    border-color: #007aff;
    background: white;
    box-shadow: 0 0 0 6rpx rgba(0, 122, 255, 0.1);
  }
}

.search-input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  font-size: 32rpx;
  color: #999;
}

/* 任务内容区域 */
.task-content {
  border-radius: 20rpx 20rpx 0 0;
  min-height: calc(100vh - 300rpx);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.task-section {
  padding: 0;
}

.task-list {
  height: calc(100vh - 400rpx);
}

/* 任务卡片样式 - 参考库存页面设计 */
.task-card {
  background: white;
  border-radius: 12rpx;
  margin: 0 20rpx 20rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  border-left: 8rpx solid #4caf50;
  transition: all 0.3s ease;

  /* 状态颜色边框 */
  &.status-pending {
    border-left-color: #f44336; /* 红色 - 待领取 */
  }

  &.status-claimed {
    border-left-color: #2196f3; /* 蓝色 - 已领取 */
  }

  &.status-progress {
    border-left-color: #ff9800; /* 黄色 - 进行中 */
  }

  &.status-completed {
    border-left-color: #4caf50; /* 绿色 - 已完成 */
  }

  &.status-paused {
    border-left-color: #ff5722; /* 橙色 - 暂停 */
  }

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.1);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 20rpx 0 20rpx;
}

.work-type-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 600;
  color: white;

  &.status-pending {
    background: #f44336; /* 红色 - 待领取 */
  }

  &.status-claimed {
    background: #2196f3; /* 蓝色 - 已领取 */
  }

  &.status-progress {
    background: #ff9800; /* 黄色 - 进行中 */
  }

  &.status-completed {
    background: #4caf50; /* 绿色 - 已完成 */
  }

  &.status-paused {
    background: #ff5722; /* 橙色 - 暂停 */
  }
}

/* 批量完成模态框样式 */
.batch-complete-dialog {
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
}

.batch-complete-content {
  max-height: 60vh;
  padding: 20rpx;
}

.batch-task-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border: 2rpx solid #e9ecef;
}

.task-info {
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #dee2e6;
}

.task-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.task-code {
  font-size: 24rpx;
  color: #666;
}

.completion-form .form-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.completion-form .form-label {
  width: 140rpx;
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

.completion-form input,
.completion-form textarea {
  flex: 1;
  padding: 12rpx 16rpx;
  border: 2rpx solid #dee2e6;
  border-radius: 8rpx;
  font-size: 26rpx;
  background: white;
}

.completion-form input:focus,
.completion-form textarea:focus {
  border-color: #007aff;
  outline: none;
}

.completion-form textarea {
  min-height: 80rpx;
}

.completion-form .form-input {
  flex: 1;
  padding: 12rpx 16rpx;
  border: 2rpx solid #dee2e6;
  border-radius: 8rpx;
  font-size: 26rpx;
  background: white;
}

.completion-form .readonly-input {
  background: #f8f9fa !important;
  color: #495057;
  border-color: #ced4da;
  cursor: not-allowed;
  text-align: center;
  font-weight: 600;
}

.batch-complete-actions {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  border-top: 2rpx solid #e9ecef;
}

.batch-complete-actions .btn {
  flex: 1;
  margin: 0 10rpx;
  padding: 16rpx 0;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 600;
  text-align: center;
}

.batch-complete-actions .btn-cancel {
  background: #f8f9fa;
  color: #6c757d;
  border: 2rpx solid #dee2e6;
}

.batch-complete-actions .confirm-btn {
  background: #007aff;
  color: white;
  border: 2rpx solid #007aff;
}

/* 协作字段样式 */
.collaboration-tag {
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.collaboration-independent {
  background: #e8f5e8;
  color: #4caf50;
}

.collaboration-cooperative {
  background: #e3f2fd;
  color: #2196f3;
}

.collaboration-segmented {
  background: #fff3e0;
  color: #ff9800;
}

.partial-claim-tag {
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.partial-claim-yes {
  background: #e8f5e8;
  color: #4caf50;
}

.partial-claim-no {
  background: #fafafa;
  color: #757575;
}

/* 多选模式样式 */
.task-card.multi-select-mode {
  position: relative;
  transition: all 0.3s ease;
}

.task-card.multi-select-mode.selected {
  border-color: #007aff;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.15);
  transform: translateY(-2rpx);
}

.select-checkbox {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 44rpx;
  height: 44rpx;
  border: 3rpx solid #dee2e6;
  border-radius: 50%;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  z-index: 10;
}

.select-checkbox.checked {
  border-color: #007aff;
  background: #007aff;
  color: white;
  transform: scale(1.1);
}

.select-checkbox .cuIcon-check {
  font-size: 24rpx;
  font-weight: bold;
}

.multi-select-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
  padding: 24rpx 32rpx;
  border-top: 2rpx solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 999;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.selected-count {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.selected-count .count-number {
  color: #007aff;
  font-size: 32rpx;
  font-weight: bold;
}

.toolbar-actions {
  display: flex;
  gap: 16rpx;
}

.toolbar-btn {
  padding: 16rpx 24rpx;
  border-radius: 24rpx;
  font-size: 26rpx;
  font-weight: 600;
  transition: all 0.2s ease;
}

.toolbar-btn.cancel {
  background: #f8f9fa;
  color: #6c757d;
  border: 2rpx solid #dee2e6;
}

.toolbar-btn.primary {
  background: #007aff;
  color: white;
  border: 2rpx solid #007aff;
}

.toolbar-btn:active {
  transform: scale(0.95);
}

.task-id {
  font-size: 24rpx;
  color: #999;
  font-weight: 500;
}

.card-content {
  padding: 16rpx 20rpx;
}

.task-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
  line-height: 1.4;
}

.task-details {
  margin-bottom: 16rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
  font-size: 24rpx;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #666;
  font-weight: 500;
  min-width: 120rpx;
  margin-right: 20rpx;
}

.detail-text {
  font-size: 24rpx;
  color: #333;
  flex: 1;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx 20rpx 20rpx;
}

.status-indicator {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;

  &.status-pending {
    background: #2196f3;
  }

  &.status-assigned {
    background: #9c27b0;
  }

  &.status-progress {
    background: #4caf50;
  }

  &.status-paused {
    background: #ff9800;
  }

  &.status-completed {
    background: #4caf50;
  }

  &.status-cancelled {
    background: #f44336;
  }
}

.task-actions {
  display: flex;
  gap: 12rpx;
}

.action-btn {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 500;
  border: none;
  color: white;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  &.primary {
    background: #2196f3;
  }

  &.success {
    background: #4caf50;
  }

  &.warning {
    background: #ff9800;
  }

  &.danger {
    background: #f44336;
  }
}

.completed-time {
  flex: 1;
  text-align: right;
}

.time-text {
  font-size: 22rpx;
  color: #999;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  color: #8e8e93;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #8e8e93;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx;
  color: #007aff;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 26rpx;
  color: #8e8e93;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .task-item {
    padding: 24rpx;
  }

  .task-title {
    font-size: 30rpx;
  }

  .task-actions {
    gap: 12rpx;

    .cu-btn {
      min-width: 100rpx;
      height: 56rpx;
      line-height: 56rpx;
      font-size: 22rpx;
      margin-bottom: 20rpx;
    }
  }
}

/* 动画效果 */
@keyframes slideInUp {
  from {
    transform: translateY(30rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.task-item {
  animation: slideInUp 0.3s ease-out;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6rpx;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3rpx;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

/* 筛选弹窗样式 */
.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.filter-content {
  width: 100%;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
}

.filter-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.cuIcon-close {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

.filter-body {
  flex: 1;
  padding: 20rpx 0;
  max-height: 60vh;
}

.filter-section {
  margin-bottom: 40rpx;
  padding: 0 40rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.filter-option {
  padding: 16rpx 24rpx;
  background: #f5f5f5;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.filter-option.active {
  background: #e3f2fd;
  color: #2196f3;
  border-color: #2196f3;
}

.filter-footer {
  display: flex;
  padding: 30rpx 40rpx;
  gap: 20rpx;
  border-top: 1rpx solid #eee;
}

.reset-btn,
.confirm-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.reset-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #2196f3;
  color: #fff;
}

.reset-btn:active {
  background: #e0e0e0;
}

.confirm-btn:active {
  background: #1976d2;
}

/* 任务领取状态字体颜色样式 */
.work-type-tag.claim-status-unclaimed {
  color: #666 !important;
  background: #f5f5f5 !important;
  border-color: #ddd !important;
}

.work-type-tag.claim-status-my-task {
  color: #4caf50 !important;
  background: #e8f5e8 !important;
  border-color: #4caf50 !important;
  font-weight: 600;
}

.work-type-tag.claim-status-others {
  color: #ff9800 !important;
  background: #fff3e0 !important;
  border-color: #ff9800 !important;
}

.work-type-tag.claim-status-default {
  color: #2196f3 !important;
  background: #e3f2fd !important;
  border-color: #2196f3 !important;
}
</style>
